/**
 * 
 */
package au.edu.swin.videoshop.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;

/**
 * @author julie
 *
 */
public class MiscUtil {
	
	//Return a new Date with all the hours. minutes, seconds and miliseconds cleared.
	public static Date normaliseDate(Date date) {
		if (date != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
	
			Calendar newCal = Calendar.getInstance();
			newCal.clear();
			newCal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
			
			return newCal.getTime();
		}
		else {
			return null;
		}
	}
	
	public static int days(Date fromDate, Date toDate) {
		Calendar from = Calendar.getInstance();
		from.setTime(normaliseDate(fromDate));
		
		Calendar to = Calendar.getInstance();
		to.setTime(normaliseDate(toDate));
		
		if (from.before(to)) {
			int days = 0;
			while (from.before(to)) {
				from.add(Calendar.DATE, 1);
				days++;
			}
			
			return days;
		}
		else if (from.after(to)) {
			int days = 0;
			while (from.after(to)) {
				from.add(Calendar.DATE, -1);
				days--;
			}
			
			return days;
		}
		else {
			return 0;
		}
	}
	
	public static Date getDay(int year, int month, int date) {
		Calendar cal = Calendar.getInstance();
		cal.clear();
		cal.set(year, month, date);
		
		return cal.getTime();
	}
	
	public static BigDecimal round(BigDecimal value) {
		if (value != null) {
			return value.setScale(2, RoundingMode.HALF_UP);
		}
		
		return null;
	}
}
